#!/usr/bin/env python

import os
import cgi

import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required

from entities import document
from actions import *

class MainHandler(webapp.RequestHandler):

    @login_required
    def get(self):
        document_id = self.request.get('document_id')
        user = users.get_current_user()
        
        if ( not user) :
            redirect(users.create_login_url("/"))
        elif (document_id == '') :
            doc = document.Document(documentName="untitled",
                                         documentType="none",
                                         documentContent=" ",
                                         documentCreator=user,
                                         isUpdated=False)
            doc.put()
            
            document_id = doc.key().id()
            self.redirect('/?document_id='+str(document_id))
        
        template_values = {
            'document_id': document_id
        }
            
        path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
        self.response.out.write(template.render(path, template_values))
        
    def getDocument(self, document_id):
        return document.Document.get_by_id(int(document_id))
        
